package spring.superrun.record.mvc.service.impl;

import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import spring.superrun.record.mvc.adapt.WxMappingJackson2HttpMessageConverter;
import spring.superrun.record.mvc.dto.WeChatLoginDto;
import spring.superrun.record.mvc.dto.WeChatMinLoginDto;
import spring.superrun.record.mvc.entity.SuperrunUserinfos;
import spring.superrun.record.mvc.dao.SuperrunUserinfosDao;
import spring.superrun.record.mvc.entity.enumlibs.ServiceResultCode;
import spring.superrun.record.mvc.entity.response.ServiceResultOfT;
import spring.superrun.record.mvc.service.SuperrunUserinfosService;
import org.springframework.stereotype.Service;
import spring.superrun.record.mvc.setup.WechatConfig;

import javax.annotation.Resource;
import java.util.List;

/**
 * (SuperrunUserinfos)表服务实现类
 *
 * @author makejava
 * @since 2021-06-18 08:33:26
 */
@Service("superrunUserinfosService")
public class SuperrunUserinfosServiceImpl implements SuperrunUserinfosService {
    @Resource
    private SuperrunUserinfosDao superrunUserinfosDao;
    @Autowired
    private WechatConfig _wechatConfig;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SuperrunUserinfos queryById(String id) {
        return this.superrunUserinfosDao.queryById(id);
    }

    @Override
    public SuperrunUserinfos queryByOpenId(String openId) {
        return superrunUserinfosDao.queryByOpenId(openId);
    }

    @Override
    public SuperrunUserinfos queryByIdHaveRecords(String id) {
        return superrunUserinfosDao.queryByIdHaveRecords(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<SuperrunUserinfos> queryAllByLimit(int offset, int limit) {
        return this.superrunUserinfosDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param superrunUserinfos 实例对象
     * @return 实例对象
     */
    @Override
    public SuperrunUserinfos insert(SuperrunUserinfos superrunUserinfos) {
        this.superrunUserinfosDao.insert(superrunUserinfos);
        return superrunUserinfos;
    }

    /**
     * 修改数据
     *
     * @param superrunUserinfos 实例对象
     * @return 实例对象
     */
    @Override
    public SuperrunUserinfos update(SuperrunUserinfos superrunUserinfos) {
        this.superrunUserinfosDao.update(superrunUserinfos);
        return this.queryById(superrunUserinfos.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.superrunUserinfosDao.deleteById(id) > 0;
    }

    /**
     * 从腾讯微信服务端获取微信用户信息基于dto
     * @param model
     * @return
     */
    @Override
    public ServiceResultOfT<SuperrunUserinfos> GetWechatUserByCodeFromTencent(WeChatMinLoginDto model) {
        ServiceResultOfT<SuperrunUserinfos> result = new ServiceResultOfT<>();
        result.IsFailed("错误没有获取到微信用户的openId");
        RestTemplate httpclient = new RestTemplate();
        httpclient.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.TEXT_PLAIN);
        if (model.getCode().isEmpty() ||model.getNickName().isEmpty()
                || model.getAvatarUrl().isEmpty())
        {
            return result.IsFailed(true, ServiceResultCode.KeyIsNull, "输入的关键信息中存在空值！");
        }
        String appid = _wechatConfig.getAppId();
        String secret = _wechatConfig.getAppSecret();
        String url = "https://api.weixin.qq.com/sns/" +
                "jscode2session?appid="+appid+"&secret="+secret+"&js_code=" +
                model.getCode()+"&grant_type=authorization_code";
        ResponseEntity<WeChatLoginDto> response =
                httpclient.getForEntity(url, WeChatLoginDto.class);
        if (response.getStatusCode().value()!=200)
        {
            result.IsFailed(response.getBody().ParseErrCode());
            return result;
        }
        WeChatLoginDto wlogin = response.getBody();
        if (null==wlogin||(wlogin.getOpenId()==null))
        {
            return result.IsFailed(true, ServiceResultCode.Failed
                    , "错误提示："+wlogin.getErrmsg());
        }
        //查找当前登录的微信用户是否被保存
        SuperrunUserinfos wechatUser = queryByOpenId(wlogin.getOpenId());
        if (null==wechatUser)
        {
            SuperrunUserinfos wechatUserModel = new SuperrunUserinfos();
            wechatUserModel.Save(model, wlogin.getOpenId());
            wechatUserModel = insert(wechatUserModel);
            if (null==wechatUserModel)
                return result.IsFailed(true,ServiceResultCode.Failed
                        ,"注册失败!");
            wechatUser = wechatUserModel;
        }
        if ((null != wechatUser) &&
                !wechatUser.VerityNickNameAndLogo(model.getNickName(), model.getAvatarUrl()))
        {
            wechatUser.setAvatarurl(model.getAvatarUrl());
            wechatUser.setNickname(model.getNickName());
            update(wechatUser);
        }
        if (null!=wechatUser.getUnionid() &&!wechatUser.getUnionid().isEmpty() &&null!=wlogin.getUnionid()
                && !wlogin.getUnionid().isEmpty())
        {
            wechatUser.setUnionid(wlogin.getUnionid());
            update(wechatUser);
        }
        if (null==wechatUser) return result;
        //检查完成
        result.IsSuccess(wechatUser, "获取微信用户信息成功！");
        return result;
    }
}
